// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// Simple extension to replace lolcat images from
// http://icanhascheezburger.com/ with loldog images instead.

//取消请求
var blockingXHR = false; //默认不取消
//请求过滤
var requestFilters = {
                urls: [ 
                  // "<all_urls>"
                  "http://192.168.2.100:8080/topui/data/*", "http://192.168.2.100:18080/test/*"
                  // "*://*/*"
                ]
              };
/*var requestFilters = {
    urls: ["<all_urls>"]
}*/



chrome.webRequest.onBeforeRequest.addListener(
  function(info) {

    /*var xhr = new XMLHttpRequest();
    xhr.open("POST", 'http://192.168.2.100:18080/test/org', false);
    xhr.onreadystatechange = function (){
      console.log(xhr)
      if (xhr.readyState == 4) {
        // WARNING! Might be evaluating an evil script!
        // var resp = eval("(" + xhr.responseText + ")");
        var resp = JSON.parse(xhr.responseText);
        console.log(resp)
        //
        
        if(resp.validate != 'success'){
          chrome.tabs.executeScript({
            // code: 'document.body.style.backgroundColor="red"'
            code: 'alert("校验失败")'
          });
          blockingXHR = true;
        }
      }
    };
    xhr.send();*/
    console.log(info);
    var url = 'http://192.168.2.100:18080/test/org',
        type = info.method, data;
    
    if (type == 'POST') {
      data = info.requestBody.formData;
      data.url = info.url;
    }else if(type == 'GET'){
      var surl = info.url;
      if(surl.indexOf('?') > 0){
        data = surl.substring(surl.indexOf('?')+1);
        data += '&url='+surl.substring(0, surl.indexOf('?'));
      }
    }else{
      data = '';
    }
    $.ajax({
      url: url,
      type: type,
      data: data,
      dataType: 'json',
      async: false,
      success: function(res){
        if(res.validate != 'success'){
          chrome.tabs.executeScript({
            // code: 'document.body.style.backgroundColor="red"'
            code: 'alert("校验失败")'
          });
          blockingXHR = true;
        }else{
          blockingXHR = false;
        }
      },
      error: function(err){
        console.log(err)
      }
    })
    
    return {
      // redirectUrl: 'http://192.168.2.100:18080/test/org'
      // redirectUrl: 'http://192.168.2.100:8080/topui/data/selectcustom32.json'
      cancel: blockingXHR
    };
  },
  // filters
  requestFilters,
  // extraInfoSpec
  ["blocking","requestBody"]);

